﻿using System;
using System.Configuration;
using System.Web.UI.WebControls;
using Shuba.Model;
using System.Collections.Generic;
using DynamicComparer;
using System.Web;

namespace Shuba.Web.bulk_upload
{
    public partial class topup_monitoring : basePage
    {
        string msg = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;
        int rowsPerPage;
        string currentPage;
        int jmlRow;

        int rowsPerPage2;
        string currentPage2;
        int jmlRow2;

        protected void Page_Load(object sender, EventArgs e)
        {
            Form.DefaultFocus = txtSearch.ClientID;
            Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("MSTR_TOPUP");
            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);
            rowsPerPage = 20;
            rowsPerPage2 = 20;

            if (!IsView)
            {
                msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitSort();
                ViewState["searchBy"] = "";
                currentPage = "1";
                ViewState["SortEx"] = "UPLOAD_DATE";
                ViewState["Sort"] = "DESC";

                currentPage2 = "1";
                ViewState["SortEx2"] = "UPLOAD_DATE";
                ViewState["Sort2"] = "DESC";

                BindData();

                LabelTitle.Text = String.Format("{0} Monitoring List", GetPageTitle("MSTR_TOPUP"));

                if (IsUserAdd(acl)){ btnUpload.Enabled = true; }
                else{ btnUpload.Enabled = false; }
            }
        }

        private void BindData()
        {
            Shuba.Business.BulkUp BI = new Shuba.Business.BulkUp();
            List<BulkUpInfo> list;
            
            if (ddlTopUpPage.Items.Count == 0 || ViewState["searchBy"].ToString() != txtSearch.Text)
                currentPage = "1";
            else currentPage = ddlTopUpPage.SelectedValue;

            jmlRow = BI.GetRowNumberTopUpMonitor(txtSearch.Text);

            list = BI.GetListTopUpMonitoring(txtSearch.Text, int.Parse(currentPage), gvList.PageSize);

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<BulkUpInfo> comparer = new DynamicComparer<BulkUpInfo>(sort);
                list.Sort(comparer);
            }

            gvList.DataSource = list;
            gvList.DataBind();
            load_data_topup_page();

            if (IsDelete) gvList.Columns[gvList.Columns.Count - 1].Visible = true;
            else gvList.Columns[gvList.Columns.Count - 1].Visible = false;
            //if (IsEdit || IsDelete) gvList.Columns[11].Visible = true; else gvList.Columns[11].Visible = false;

            //FOR APPROVAL GRID
            if (IsChecker)
            {
                BindApprovalData();
                if (ApprovalGrid.Rows.Count > 0) { ApprovalPnl.Visible = true; } else { ApprovalPnl.Visible = false; }
            }
        }

        protected void load_data_topup_page()
        {
            int jmlHal = (int)Math.Ceiling((decimal)jmlRow / (decimal)rowsPerPage);
            string pageNum;

            footLink.Visible = (jmlHal > 0);

            ddlTopUpPage.Items.Clear();
            for (int i = 0; i < jmlHal; i++)
            {
                pageNum = (i + 1).ToString();
                ddlTopUpPage.Items.Add(new ListItem(pageNum, pageNum));
            }

            if (ViewState["searchBy"].ToString() == txtSearch.Text)
                ddlTopUpPage.SelectedValue = currentPage;
            ViewState["searchBy"] = txtSearch.Text;

            lblPage.Text = "Page " + currentPage + " of " + jmlHal;

            firstLink.Visible = true;
            prevLink.Visible = true;
            nextLink.Visible = true;
            lastLink.Visible = true;

            if (ddlTopUpPage.SelectedIndex <= 0)
            {
                firstLink.Visible = false;
                prevLink.Visible = false;
            }
            if (ddlTopUpPage.SelectedIndex >= ddlTopUpPage.Items.Count - 1)
            {
                nextLink.Visible = false;
                lastLink.Visible = false;
            }
        }

        protected void ddlTopUpPage_IndexChange(object sender, EventArgs e)
        {
            BindData();
        }

        protected void linkDataPage_Click(object sender, EventArgs e)
        {
            if (sender == firstLink)
                ddlTopUpPage.SelectedIndex = 0;
            else if (sender == prevLink)
                ddlTopUpPage.SelectedIndex--;
            else if (sender == nextLink)
                ddlTopUpPage.SelectedIndex++;
            else if (sender == lastLink)
                ddlTopUpPage.SelectedIndex = ddlTopUpPage.Items.Count - 1;
            BindData();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            /*if (UPLOAD_TYPE == "TOPUP")
            {
                Response.Redirect("topup_list_failed.aspx?a=ed&id=" + BATCH_ID);
            }*/
            if (e.CommandName == "Remove")
            {
                Shuba.Business.BulkUp BI = new Shuba.Business.BulkUp();
                string[] PARAM = e.CommandArgument.ToString().Split('~');
                string BATCH_ID = PARAM[0];
                string UPLOAD_TYPE = PARAM[1];

                try
                {
                    BI.delete(BATCH_ID,UPLOAD_TYPE);
                    AddLog("DELETE", "DELETE PIPELINE");
                }
                catch (Exception ex)
                {
                    msg = ex.Message.ToString();
                    ErrBox.Visible = true;
                    ErrMsg.Text = msg;
                }

                if (msg == "") RestartPage();
            }
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[4].Text == "RUNNING") 
                {
                    e.Row.Cells[6].Enabled = false;
                    e.Row.Cells[7].Enabled = false;
                    e.Row.Cells[8].Enabled = false;
                }               

                LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");
                if (IsDelete)
                {
                    //string BATCH_ID = e.Row.Cells[0].Text;
                    //Shuba.Business.BulkUp bu = new Shuba.Business.BulkUp();
                    //int jumlahBaris = bu.GetRowNumberTopupbyBatchID(BATCH_ID);
                    //if (jumlahBaris > 0)
                    //{
                        btnDelete.Enabled = true;
                    //}
                    //else
                    //{
                        //btnDelete.Enabled = false;
                        //btnDelete.OnClientClick = "";
                    //}
                }
                else
                {
                    btnDelete.Enabled = false;
                    btnDelete.OnClientClick = "";
                }
            }
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;
            BindData();
        }

        /*======================================
               APPROVAL GRID START HERE
        =======================================
        */
        private void BindApprovalData()
        {
            Shuba.Business.BulkUp BI = new Shuba.Business.BulkUp();
            List<BulkUpInfo> list;// = BI.GetListTopupApproval(txtSearch.Text, "BATCH_ID");

            /*if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<TopUpBulkInfo> comparer = new DynamicComparer<TopUpBulkInfo>(sort);
                list.Sort(comparer);
            }*/
            if (ddlApproval.Items.Count == 0)
                currentPage2 = "1";
            else currentPage2 = ddlApproval.SelectedValue;
            string sortby = ViewState["SortEx2"].ToString();
            string dir = ViewState["Sort2"].ToString();

            list = BI.GetListApprovalTopUpMonitoring(HttpContext.Current.User.Identity.Name,txtSearch.Text, int.Parse(currentPage2), rowsPerPage2, sortby, dir);
            jmlRow2 = BI.GetRowNumberApprovalTopUpMonitor(HttpContext.Current.User.Identity.Name,txtSearch.Text);

            load_data_ApprovalTopup_page();
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        // start ++
        protected void load_data_ApprovalTopup_page()
        {
            int jmlHal = (int)Math.Ceiling((decimal)jmlRow2 / (decimal)rowsPerPage2);
            string pageNum;

            footLinkApproval.Visible = (jmlHal > 0);

            ddlApproval.Items.Clear();
            for (int i = 0; i < jmlHal; i++)
            {
                pageNum = (i + 1).ToString();
                ddlApproval.Items.Add(new ListItem(pageNum, pageNum));
            }

            ddlApproval.SelectedValue = currentPage2;
            lblPageApproval.Text = "Page " + currentPage2 + " of " + jmlHal;

            firstLinkApproval.Visible = true;
            prevLinkApproval.Visible = true;
            nextLinkApproval.Visible = true;
            lastLinkApproval.Visible = true;

            if (ddlApproval.SelectedIndex <= 0)
            {
                firstLinkApproval.Visible = false;
                prevLinkApproval.Visible = false;
            }

            if (ddlApproval.SelectedIndex >= ddlApproval.Items.Count - 1)
            {
                nextLinkApproval.Visible = false;
                lastLinkApproval.Visible = false;
            }
        }

        protected void ddlApproval_IndexChange(object sender, EventArgs e)
        {
            BindApprovalData();
        }

        protected void linkDataApprovalPage_Click(object sender, EventArgs e)
        {
            if (sender == firstLinkApproval)
                ddlApproval.SelectedIndex = 0;
            else if (sender == prevLinkApproval)
                ddlApproval.SelectedIndex--;
            else if (sender == nextLinkApproval)
                ddlApproval.SelectedIndex++;
            else if (sender == lastLinkApproval)
                ddlApproval.SelectedIndex = ddlApproval.Items.Count - 1;
            BindData();
        }
        // end ++

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[5].Text == "P") { e.Row.Cells[4].Text = "PENDING"; }
                else { e.Row.Cells[5].Text = ""; }

                if (e.Row.Cells[9].Text == "1") { e.Row.Cells[9].Text = "DELETE"; }
                else if (e.Row.Cells[9].Text == "0") { e.Row.Cells[9].Text = "INSERT"; }
            }
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                if (chkItemSelect.Checked)
                {
                    string BATCH_ID = ApprovalGrid.DataKeys[row.RowIndex].Values["BATCH_ID"].ToString();
                    string IS_DELETE = ApprovalGrid.DataKeys[row.RowIndex].Values["IS_DELETED"].ToString();

                    if (Approve(BATCH_ID,IS_DELETE, true))
                    {
                        SuccessCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\n\\nFailed to Approve : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);

        }

        /*protected void btnApproveAll_Click(object sender, EventArgs e)
        {
            int[] countStatus = ApproveAll("A");
            int success = 0;
            foreach (int item in countStatus)
            {
                success += item;
            }
            string msg = "Approval Notification\\n\\nTotal record to approve : " + success + " Record(s)\\nSuccessfully Insert : " + countStatus[0] + " Record(s)\\nSuccessfully Update : " + countStatus[1] + " Record(s)\\nSuccessfully Delete : " + countStatus[2] + " Record(s)";

            BindData();
            Alert(msg);
        }*/

        protected void btnReject_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                if (chkItemSelect.Checked)
                {
                    string BATCH_ID = ApprovalGrid.DataKeys[row.RowIndex].Values["BATCH_ID"].ToString();
                    string IS_DELETE = ApprovalGrid.DataKeys[row.RowIndex].Values["IS_DELETED"].ToString();

                    if (Approve(BATCH_ID, IS_DELETE, false))
                    {
                        SuccessCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nSuccessfully Reject : " + SuccessCount + " Record(s)\\n\\nFailed to Reject : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);

        }

        /*protected void btnRejectAll_Click(object sender, EventArgs e)
        {
            int[] countStatus = ApproveAll("R");
            int success = 0;
            foreach (int item in countStatus)
            {
                success += item;
            }
            string msg = "Approval Notification\\n\\nTotal record to reject : " + success + " Record(s)\\nSuccessfully reject Insert : " + countStatus[0] + " Record(s)\\nSuccessfully reject Update : " + countStatus[1] + " Record(s)\\nSuccessfully reject Delete : " + countStatus[2] + " Record(s)";

            BindData();
            Alert(msg);
        }*/

        private bool Approve(string BATCH_ID, string is_delete, bool IsApprove)
        {
            bool approve = false;
            string ActType = "I";

            Shuba.Business.BulkUp BI = new Shuba.Business.BulkUp();
            //BATCH_ID = Server.HtmlDecode(BATCH_ID).Trim();
            if (IsApprove)
            {
                if (BATCH_ID != "" && is_delete != "")
                {
                    try
                    {
                        AddLog("APPROVAL", "APPROVE TOPUP MONITORING");
                        if (BI.ApproveTopupMonitoring(BATCH_ID,is_delete) > 0)
                        {
                            approve = true;
                        }
                        else
                        {
                            approve = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        approve = false;
                        ErrBox.Visible = true;
                        ErrMsg.Text = ex.Message;
                    }
                }
            }
            else
            {
                AddLog("APPROVAL", "REJECT TOPUP MONITORING");
                if (BI.reject(BATCH_ID, is_delete) > 0)
                {
                    approve = true;
                }
                else
                {
                    approve = false;
                }
            }
            return approve;
        }

        /*private int[] ApproveAll(string status)
        {
            Shuba.Business.BulkUp BI = new Shuba.Business.BulkUp();
            int[] countStatus = BI.ApproveMonitoring(status);

            if (status == "A")
            {
                AddLog("APPROVAL", "APPROVE TOPUP MONITORING");
            }
            else
            {
                AddLog("APPROVAL", "REJECT TOPUP MONITORING");
            }
            return countStatus;
        }*/
    }
}